package com.bit.forum.interceptor;

import com.bit.forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String loginUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION)!=null) {
            return true;
        }
        //校验url是否正确
        if(!loginUrl.startsWith("/")){
            loginUrl="/"+loginUrl;
        }
        //校验不通过 跳转到登录页面
        response.sendRedirect(loginUrl);
        //中断流程
        return false;
    }
}
